package jumeng

import (
	"encoding/xml"
	"fmt"
	log "gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/msg/sms/model"
	"gitee.com/sansaniot/ssiot-core/utils"
	"strings"

	"net/url"
)

type ReturnSMS struct {
	Result xml.Name `xml:"returnsms"`
	Code   string   `xml:"result"`
	Desc   string   `xml:"desc"`
	TaskId string   `xml:"taskid"`
}

type Sdk struct {
	Config *model.SMSConfig `json:"sms_config,omitempty"`
}

// 发送短信
func (app *Sdk) SendSms(phone, content string) (string, error) {
	if !strings.HasSuffix(content, "【三三物联】") {
		content = "【三三物联】" + content
	}
	server := "http://smsjm.jxtebie.com/sms/submit"
	param := url.Values{}
	//param.Add("spid", "600220")
	//param.Add("password", "Xw4kpIG91")
	//param.Add("ac", "1069600220")
	//param.Add("mobiles", "15527557427,15527557427")
	//param.Add("content", "【三三物联1】您的验证码为：${captcha}，该验证码5分钟内有效，请勿泄露给他人。")

	param.Add("spid", app.Config.AccessKeyId)
	param.Add("password", app.Config.AccessKeySecret)
	param.Add("ac", app.Config.SignName)
	param.Add("mobiles", phone)
	param.Add("content", content)

	//发送短信
	res, err := utils.HttpPostXml(server, param)
	if err != nil {
		return "", err
	}

	//解析发送任务状态
	var result ReturnSMS
	err = xml.Unmarshal(res, &result)
	if err != nil {
		return "", err
	}
	log.Info(fmt.Sprintf("send sms task ok. data=%s, code=%s, desc=%s, taskId=%s", content, result.Code, result.Desc, result.TaskId))

	//获取响应状态
	res2, err2 := app.GetSendStatus(result.TaskId, phone)
	if err2 != nil {
		return "", err2
	}
	log.Info(fmt.Sprintf("send sms data ok. data=%s", res2))
	return result.Desc, nil
}

// 获取发送状态
func (app *Sdk) GetSendStatus(taskId string, phone string) (string, error) {
	server := "http://baljm.jxtebie.com/xunjintec/intfgwsms/spreport.html"
	param := url.Values{}
	param.Add("spid", app.Config.AccessKeyId)
	param.Add("password", app.Config.AccessKeySecret)
	param.Add("action", "queryreport")
	param.Add("mobile", phone)
	param.Add("taskid", taskId)

	res, err := utils.HttpPostXml(server, param)
	if err != nil {
		return "", err
	}
	var result ReturnSMS
	err = xml.Unmarshal(res, &result)
	log.Info(string(res))
	return result.Desc, err
}
